<template>
  <div>
    <el-drawer
      v-model="darwer"
      title="分配按钮权限"
      @open="openDarwer"
      @close="closeDarwer"
    >
      <el-checkbox
        v-model="checkAll"
        :indeterminate="isIndeterminate"
        @change="handleCheckAllChange"
      >
        全选
      </el-checkbox>
      <el-checkbox-group
        v-model="checkedCities"
        @change="handleCheckedCitiesChange"
      >
        <el-checkbox
          v-for="city in btnList"
          :key="city._id"
          :label="city.ButtonName"
          :value="city._id"
        >
          {{ city.ButtonName }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="closeDarwer">取消</el-button>
        <el-button type="primary" @click="AddJobBtn">确定</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
defineOptions({
  name: "BtnJob",
});
const props = defineProps(["modelValue", "btnId"]);
const emits = defineEmits(["update:modelValue", "update:btnId", "getJobList"]);
import { getBtnListAPI } from "@/api/btn";
import { assignButtonAPI, getJobButtonAPI } from "@/api/job";
import { ElMessage } from "element-plus";
import { ref, watch, computed } from "vue";
let darwer = ref(props.modelValue);
let btnId = ref(props.btnId);
let btnList = ref([]);
let checkedCities = ref([]);
let checkAll = ref(false);
let isIndeterminate = computed(() => {
  return (
    checkedCities.value.length > 0 &&
    checkedCities.value.length < btnList.value.length
  );
});
watch(
  () => props.modelValue,
  (newValue) => {
    darwer.value = newValue;
    emits("update:modelValue", darwer.value);
  }
);
watch(
  () => props.btnId,
  (newValue) => {
    btnId.value = newValue;
    emits("update:btnId", btnId.value);
  }
);
const closeDarwer = () => {
  darwer.value = false;
  btnId.value = "";
  emits("update:btnId", "");
  emits("update:modelValue", darwer.value);
};
const openDarwer = async () => {
  let result = await getBtnListAPI();
  btnList.value = result.data.list;
  getBtnJob();
};
const handleCheckAllChange = (val) => {
  console.log(val);
  checkedCities.value = val ? btnList.value.map((item) => item._id) : [];
};
const handleCheckedCitiesChange = (value) => {
  let checkedCount = value.length;
  checkAll.value = checkedCount === btnList.value.length;
};
//获取对应职位的按钮权限
const getBtnJob = async () => {
  let result = await getJobButtonAPI(btnId.value);
  checkedCities.value = result.data.map((item) => item.btnId._id);
  checkAll.value = checkedCities.value.length === btnList.value.length
};
const AddJobBtn = async () => {
  let result = await assignButtonAPI({
    jobId: btnId.value,
    buttonArr: checkedCities.value,
  });
  if (result.code == 200) {
    closeDarwer();
    ElMessage.success("分配成功");
    emits('getJobList')
  }
};
</script>

<style lang="scss" scoped></style>
